const { Controller } = require("egg");
const checkUserAgent = require("../util/checkUserAgent");

class BlogController extends Controller {
    //添加博客
    async create() {
            try {
                const body = this.ctx.request.body
                await this.ctx.service.blog.addBlog(body)
                this.ctx.body = {
                    code: 20000,
                    message: true,

                }
            } catch (error) {
                this.ctx.body = {
                    code: 50000,
                    message: false
                }
            }
        }
        //获取博客
    async index() {
            try {
                const query = this.ctx.request.query
                const data = await this.ctx.service.blog.getBlog(query)
                this.ctx.body = {
                    code: 20000,
                    message: true,
                    data: data
                }
            } catch (error) {
                this.ctx.body = {
                    code: 50000,
                    message: false,
                }
            }
        }
        //删除博客
    async destroy() {
            try {
                const id = this.ctx.params.id
                await this.ctx.service.blog.deleteBlog(id)
                this.ctx.body = {
                    code: 20000,
                    message: true,
                }
            } catch (error) {
                this.ctx.body = {
                    code: 50000,
                    message: false,
                }
            }
        }
        //更新博客
    async update() {
        try {
            const body = this.ctx.request.body
            const id = this.ctx.params.id
            await this.ctx.service.blog.updateBlog(id, body)
            this.ctx.body = {
                code: 20000,
                message: true,
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false,
            }
        }
    }

    async getBlogList() {
        const { ctx } = this;
        const ua = checkUserAgent(ctx.header['user-agent'])
        const data = await this.service.website.getBlogList()
        if (ua) {
            await ctx.render("pc/blog.html",data )

        } else {
            await ctx.render("mobile/blog.html",data)
        }
    }
    async getBlogDetail() {
        const { ctx } = this;
        const ua = checkUserAgent(ctx.header['user-agent'])
        let id = ctx.params.id
        const data = await this.service.website.getBlogDetail(id)
        if(ua){
            await ctx.render("pc/blogDetail.html", data )
        }else{
            await ctx.render("mobile/blogDetail.html", data )
        }
    }

}
module.exports = BlogController